<template>
    <el-container>
        <!-- 顶部导航栏 -->
        <el-header class="header">
            <h1 style="padding: 0 20px;">管理主页</h1>
            <div>
                <el-button type="success" size="small" @click="goToCostAnalysis" style="margin-right: 5px">成本分析</el-button>
                <el-button type="primary" size="small" @click="goToTimeCost" style="margin-right: 5px">工时费发放记录</el-button>
                <el-button type="danger" size="small" @click="handleLogout">退出登录</el-button>
            </div>
        </el-header>

        <!-- 主内容区域 -->
        <el-main>
            <div style="display: flex;align-items: center;gap: 10px;" >
                <h2 style="padding: 0 20px;">用户信息</h2>
                <el-button type="success" size="default" @click="insertUser()"> 新增 </el-button>
            </div>
            <div class="table-container">
                <el-table :data="userData" border stripe>
                    <el-table-column prop="user_id" label="用户ID" class="custom-column" />
                    <el-table-column prop="username" label="用户名" class="custom-column" />
                    <el-table-column prop="password" label="密码" class="custom-column" />
                    <el-table-column label="操作" class="custom-column" #default="scope">
                        <el-button type="primary" size="small" @click="changeUserInfo(scope.row)"> 修改 </el-button>
                        <el-button type="danger" size="small" @click="deleteUser(scope.row.user_id)"> 删除 </el-button>
                    </el-table-column>
                </el-table>
            </div>

            <div style="display: flex;align-items: center;gap: 10px;" >
                <h2 style="padding: 0 20px;">维修人员信息</h2>
                <el-button type="success" size="default" @click="insertRepairPerson()"> 新增 </el-button>
            </div>
            <div class="table-container">
                <el-table :data="repairPersonData" border stripe>
                    <el-table-column prop="user_id" label="用户ID" class="custom-column" />
                    <el-table-column prop="username" label="用户名" class="custom-column" />
                    <el-table-column prop="password" label="密码" class="custom-column" />
                    <el-table-column prop="repair_person_id" label="维修人员ID" class="custom-column" />
                    <el-table-column prop="specialty" label="工种" class="custom-column" />
                    <el-table-column prop="hourly_rate" label="时薪" class="custom-column"/>
                    <el-table-column label="操作" class="custom-column" #default="scope">
                        <el-button type="primary" size="small" @click="changeRepairPersonInfo(scope.row)"> 修改 </el-button>
                        <el-button type="danger" size="small" @click="deleteRepairPerson(scope.row.user_id, scope.row.repair_person_id)"> 删除 </el-button>
                    </el-table-column>
                </el-table>
            </div>

            <div style="display: flex; align-items: center; gap: 10px;">
                <h2 style="padding: 0 20px;">车辆信息</h2>
                <el-button type="success" size="default" @click="insertVehicle">新增车辆</el-button>
            </div>
            <div class="table-container">
                <el-table :data="vehicleData" border stripe>
                    <el-table-column prop="vehicle_id" label="车辆ID" />
                    <el-table-column prop="user_id" label="用户ID" />
                    <el-table-column prop="license_plate" label="车牌号" />
                    <el-table-column prop="model" label="车型" />
                    <el-table-column prop="manufacture_year" label="生产年份" />
                    <el-table-column label="操作">
                        <template #default="{ row }">
                            <el-button type="primary" size="small" @click="changeVehicleInfo(row)">修改</el-button>
                            <el-button type="danger" size="small" @click="deleteVehicle(row.vehicle_id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 订单数据筛选 -->
            <div style="display: flex; align-items: center; gap: 10px;">
                <h2 style="padding: 0 20px;">订单信息</h2>
                <el-button type="success" size="default" @click="insertOrder">新增订单</el-button>
            </div>
            <div class="table-container">
                <el-table :data="repairOrderData" border stripe>
                    <el-table-column prop="order_id" label="订单ID" />
                    <el-table-column prop="vehicle_id" label="车辆ID" />
                    <el-table-column prop="user_id" label="用户ID" />
                    <el-table-column prop="create_time" label="创建时间">
                        <template #default="{ row }">
                            {{row.create_time ? row.create_time : "暂无" }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="complete_time" label="完成时间">
                        <template #default="{ row }">
                            {{row.complete_time ? row.complete_time : "暂无" }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="total_cost" label="总费用">
                        <template #default="{ row }">
                            ￥{{ row.total_cost.toFixed(2) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="status" label="订单状态">
                        <template #default="{ row }">
                            {{ row.status ? '已完成' : '进行中' }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="payment_status" label="支付状态">
                        <template #default="{ row }">
                            {{ row.payment_status ? '已支付' : '未支付' }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template #default="{ row }">
<!--                            <el-button-->
<!--                                type="primary"-->
<!--                                size="small"-->
<!--                                @click="updateOrderStatus(row.order_id, !row.status)">-->
<!--                                {{ row.status ? '标记为进行中' : '标记为已完成' }}-->
<!--                            </el-button>-->
                            <el-button
                                type="danger"
                                size="small"
                                @click="deleteOrder(row.order_id)">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 车型统计 -->
            <h2 style="padding: 0 20px;">车型统计数据</h2>
            <div class="table-container">
                <el-table :data="vehicleModelStatistics" border stripe>
                    <el-table-column prop="model" label="车型" width="180" />
                    <el-table-column prop="repairedTimes" label="维修次数" sortable />
                    <el-table-column label="平均维修费用">
                        <template #default="{row}">
                            ￥{{ row.averageRepairCost.toFixed(2) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="维修频率">
                        <template #default="{row}">
                            {{ row.repairedFrequency }}次/辆
                        </template>
                    </el-table-column>
                    <el-table-column prop="theMostRiskType" label="最常见故障类型" />
                </el-table>
            </div>

            <!-- 负面反馈工单 -->
            <h2 style="padding: 0 20px;">负面反馈工单</h2>
            <div class="table-container" style="margin-bottom: 20px;">
                <el-table :data="filteredNegativeFeedbacks" border>
                    <el-table-column prop="assignmentId" label="任务ID" />
                    <el-table-column prop="orderId" label="订单ID" />
                    <el-table-column prop="repairPersonId" label="员工ID" />
                </el-table>
            </div>

            <!-- 工种统计 -->
            <h2 style="padding: 0 20px;">工种接待任务数据</h2>
            <div class="table-container">
                <div style="margin-bottom: 10px;">
                    <span style="margin-right: 10px;">选择最近几个月：</span>
                    <el-select v-model="selectedMonth" style="width: 120px;">
                        <el-option
                            v-for="m in 12"
                            :key="m"
                            :label="`${m}`"
                            :value="m"
                        />
                    </el-select>
                </div>
                <el-table :data="taskTypeAssignments" border>
                    <el-table-column label="工种类型">
                        <template #default="{row}">
                            {{ typeLabelMap[row.taskType] || row.taskType }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="completedAssignmentsCount" label="完成任务数" />
                    <el-table-column label="占比">
                        <template #default="{row}">
                            {{ row.assignmentPercentage.toFixed(1) }}%
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <h2 style="padding: 0 20px;">零件信息</h2>
            <div class="table-container">
                <el-table :data="partData" border stripe>
                    <el-table-column prop="part_id" label="零件ID" class="custom-column" />
                    <el-table-column prop="part_name" label="零件名称" class="custom-column" />
                    <el-table-column prop="unit_price" label="单价（元）" class="custom-column">
                        <template #default="{ row }">
                            ￥{{ row.unit_price.toFixed(2) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="taskType" label="任务类型" class="custom-column">
                        <template #default="{ row }">
                            {{ typeLabelMap[row.taskType] || row.taskType }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="stock_quantity" label="库存数量" class="custom-column" />
                </el-table>
            </div>

        </el-main>
    </el-container>

    <el-dialog
        title="修改用户数据"
        v-model="changeUserVisible"
        width="30%"
        @close="closeUserDialog"
    >
        <el-form :model="currentUser" ref="userForm" label-width="80px" :rules="userRules">
            <el-form-item label="用户ID">
                <el-input v-model="currentUser.user_id" disabled />
            </el-form-item>
            <el-form-item label="用户名" prop="username">
                <el-input v-model="currentUser.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="currentUser.password" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="closeUserDialog">取消</el-button>
            <el-button type="primary" @click="submitUserForm">提交</el-button>
        </template>
    </el-dialog>

    <el-dialog
        title="新增用户"
        v-model="addUserVisible"
        width="30%"
        @close="closeInsertUserDialog"
    >
        <el-form :model="currentUser" ref="insertUserForm" label-width="80px" :rules="userRules">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="currentUser.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="currentUser.password" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="closeInsertUserDialog">取消</el-button>
            <el-button type="primary" @click="submitInsertUserForm">提交</el-button>
        </template>
    </el-dialog>

    <el-dialog
        title="修改维修人员数据"
        v-model="changeRepairPersonVisible"
        width="30%"
        @close="closeRepairPersonDialog"
    >
        <el-form :model="currentRepairPerson" ref="repairPersonForm" label-width="100px" :rules="repairPersonRules">
            <el-form-item label="维修人员ID">
                <el-input v-model="currentRepairPerson.repair_person_id" disabled />
            </el-form-item>
            <el-form-item label="用户名" prop="username">
                <el-input v-model="currentRepairPerson.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="currentRepairPerson.password" />
            </el-form-item>
            <el-form-item label="时薪" prop="hourly_rate">
                <el-input v-model="currentRepairPerson.hourly_rate" />
            </el-form-item>
            <el-select v-model="currentRepairPerson.specialty" placeholder="请选择工种" style="margin-top: 5px; width: 300px;margin-left: 100px">
                <el-option label="漆工" value="PAINTER" />
                <el-option label="焊工" value="WELDER" />
                <el-option label="机修" value="MECHANIC" />
                <el-option label="电工" value="ELECTRICIAN" />
            </el-select>
        </el-form>
        <template #footer>
            <el-button @click="closeRepairPersonDialog">取消</el-button>
            <el-button type="primary" @click="submitRepairPersonForm">提交</el-button>
        </template>
    </el-dialog>

    <el-dialog
        title="新增维修人员数据"
        v-model="addRepairPersonVisible"
        width="30%"
        @close="closeInsertRepairPersonDialog"
    >
        <el-form :model="currentRepairPerson" ref="insertRepairPersonForm" label-width="100px" :rules="repairPersonRules">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="currentRepairPerson.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="currentRepairPerson.password" />
            </el-form-item>

            <el-form-item label="时薪" prop="hourly_rate">
                <el-input v-model="currentRepairPerson.hourly_rate" />
            </el-form-item>
            <el-select v-model="currentRepairPerson.specialty" placeholder="请选择工种" style="margin-top: 5px; width: 300px;margin-left: 100px">
                <el-option label="漆工" value="PAINTER" />
                <el-option label="焊工" value="WELDER" />
                <el-option label="机修" value="MECHANIC" />
                <el-option label="电工" value="ELECTRICIAN" />
            </el-select>
        </el-form>
        <template #footer>
            <el-button @click="closeInsertRepairPersonDialog">取消</el-button>
            <el-button type="primary" @click="submitInsertRepairPersonForm">提交</el-button>
        </template>
    </el-dialog>

    <el-dialog
        title="新增维修订单"
        v-model="addOrderVisible"
        width="30%"
        @close="addOrderVisible = false"
    >
        <el-form :model="currentOrder" label-width="100px">
            <el-form-item label="车辆ID">
                <el-input v-model="currentOrder.vehicle_id" />
            </el-form-item>
            <el-form-item label="用户ID">
                <el-input v-model="currentOrder.user_id" />
            </el-form-item>
            <el-form-item label="总费用">
                <el-input v-model="currentOrder.total_cost" />
            </el-form-item>
            <el-form-item label="订单状态">
                <el-switch v-model="currentOrder.status" active-text="已完成" inactive-text="进行中" />
            </el-form-item>
            <el-form-item label="工种">
                <el-checkbox-group v-model="currentOrder.taskTypes">
                    <el-checkbox label="PAINTER">漆工</el-checkbox>
                    <el-checkbox label="WELDER">焊工</el-checkbox>
                    <el-checkbox label="MECHANIC">机修</el-checkbox>
                    <el-checkbox label="ELECTRICIAN">电工</el-checkbox>
                </el-checkbox-group>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="addOrderVisible = false">取消</el-button>
            <el-button type="primary" @click="submitInsertOrderForm">提交</el-button>
        </template>
    </el-dialog>

    <el-dialog
        title="新增车辆"
        v-model="addVehicleVisible"
        width="30%"
        @close="closeInsertVehicleDialog"
    >
        <el-form :model="currentVehicle" ref="insertVehicleForm" label-width="100px" :rules="vehicleRules">
            <el-form-item label="用户ID" prop="user_id">
                <el-input v-model="currentVehicle.user_id" />
            </el-form-item>
            <el-form-item label="车牌号" prop="license_plate">
                <el-input v-model="currentVehicle.license_plate" />
            </el-form-item>
            <el-form-item label="车型" prop="model">
                <el-input v-model="currentVehicle.model" />
            </el-form-item>
            <el-form-item label="生产年份" prop="manufacture_year">
                <el-input v-model="currentVehicle.manufacture_year" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="closeInsertVehicleDialog">取消</el-button>
            <el-button type="primary" @click="submitInsertVehicleForm">提交</el-button>
        </template>
    </el-dialog>

    <el-dialog
        title="修改车辆信息"
        v-model="changeVehicleVisible"
        width="30%"
        @close="closeVehicleDialog"
    >
        <el-form :model="currentVehicle" ref="vehicleForm" label-width="100px" :rules="vehicleRules">
            <el-form-item label="车辆ID">
                <el-input v-model="currentVehicle.vehicle_id" disabled />
            </el-form-item>
            <el-form-item label="用户ID" prop="user_id">
                <el-input v-model="currentVehicle.user_id" />
            </el-form-item>
            <el-form-item label="车牌号" prop="license_plate">
                <el-input v-model="currentVehicle.license_plate" />
            </el-form-item>
            <el-form-item label="车型" prop="model">
                <el-input v-model="currentVehicle.model" />
            </el-form-item>
            <el-form-item label="生产年份" prop="manufacture_year">
                <el-input v-model="currentVehicle.manufacture_year" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="closeVehicleDialog">取消</el-button>
            <el-button type="primary" @click="submitVehicleForm">提交</el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import router from "@/router";
import { getNegativeFeedbackApi, getTaskTypeAssignmentApi, getVmodelsApi } from '@/api/progress';
import {
    createRepairPersonApi,
    deleteUserApi,
    getAllRepairPersonsApi,
    getAllUsersApi, registerApi,
    updateRepairPersonApi,
    updateUserApi
} from "@/api/user";
import {
    createOrderApi,
    deleteOrderApi,
    getAllOrdersApi,
    // getRepairOrderByIdApi,
    // updateOrderStatusApi
} from "@/api/order";
import {
    getAllVehiclesApi,
    createVehicleApi,
    updateVehicleApi,
    deleteVehicleApi
} from '@/api/vehicle';
import { getAllPartsApi } from '@/api/part'; // 假设后端接口已定义


const typeLabelMap = {
    PAINTER: '漆工',
    WELDER: '焊工',
    MECHANIC: '机修',
    ELECTRICIAN: '电工'
};

// 车型统计数据
const vehicleModelStatistics = ref([]);
// 负面反馈数据
const negativeFeedbacks = ref([]);
// 工种统计数据
const taskTypeAssignments = ref([]);
// 筛选条件
const selectedMonth = ref(new Date().getMonth() + 1);
const filterRepairPersonId = ref('');
const userData = ref([]);
const repairPersonData = ref([]);
const repairOrderData = ref([]);

const changeUserVisible = ref(false);
const changeRepairPersonVisible = ref(false);
//当前激活的用户id
const currentUser = ref(null);
const currentRepairPerson = ref(null);
//零件数据
const partData = ref([]);
// 加载零件数据
const fetchPartData = async () => {
    try {
        const res = await getAllPartsApi();
        partData.value = res.data.map(item => ({
            ...item,
            taskType: typeLabelMap[item.taskType] || item.taskType // 转换任务类型
        }));
    } catch (error) {
        ElMessage.error('零件数据加载失败');
    }
};

const deleteUser = async (userId) => {
    try {
        const res = await deleteUserApi(userId);
        if (res.data) {
            ElMessage.success('用户删除成功');
            await fetchUserData(); // 刷新用户数据
        } else {
            ElMessage.error('用户删除失败');
        }
    } catch (error) {
        ElMessage.error('网络请求失败');
    }
};

const deleteRepairPerson = async (userId) => {
    try {
        // 会级联删除
        const res = await deleteUserApi(userId);
        if (res.data) {
            ElMessage.success('维修人员删除成功');
            await fetchRepairPersonData(); // 刷新维修人员数据
        } else {
            ElMessage.error('维修人员删除失败');
            console.log(res)
        }
    } catch (error) {
        ElMessage.error('网络请求失败');
    }
};

const addUserVisible = ref(false);
const addRepairPersonVisible = ref(false);
const insertUser = () => {
    currentUser.value = {
        user_id: null,
        username: '',
        password: ''
    };
    addUserVisible.value = true;
};
const insertRepairPerson = () => {
    currentRepairPerson.value = {
        user_id: null,
        username: '',
        password: '',
        repair_person_id: null,
        specialty: '',
        hourly_rate: ''
    };
    addRepairPersonVisible.value = true;
}
const changeUserInfo = (user) => {
    currentUser.value = user;
    changeUserVisible.value = true;
};
const changeRepairPersonInfo = (repairPerson) => {
    currentRepairPerson.value = repairPerson;
    changeRepairPersonVisible.value = true;
};

const closeUserDialog = () => {
    const form = userForm.value;
    if (form) {
        form.resetFields(); // 重置用户表单
    }
    changeUserVisible.value = false; // 关闭用户对话框
};
const closeInsertUserDialog = () => {
    const form = insertUserForm.value;
    if (form) {
        form.resetFields(); // 重置用户表单
    }
    addUserVisible.value = false; // 关闭新增用户对话框
}

const closeRepairPersonDialog = () => {
    const form = repairPersonForm.value;
    if (form) {
        form.resetFields(); // 重置维修人员表单
    }
    changeRepairPersonVisible.value = false; // 关闭维修人员对话框
};
const closeInsertRepairPersonDialog = () => {
    const form = insertRepairPersonForm.value;
    if (form) {
        form.resetFields(); // 重置维修人员表单
    }
    addRepairPersonVisible.value = false; // 关闭新增维修人员对话框
}

// const updateOrderStatus = async (orderId, status) => {
//     try {
//         let order = await getRepairOrderByIdApi(orderId);
//         if (order.data == null) {
//             ElMessage.error('订单不存在');
//             return;
//         }
//         order.data.status = status; // 更新订单状态
//         const res = await updateOrderStatusApi(order.data);
//         if (res.data) {
//             ElMessage.success('订单状态更新成功');
//             await fetchOrderData(); // 刷新订单数据
//         } else {
//             ElMessage.error('订单状态更新失败');
//         }
//     } catch (error) {
//         ElMessage.error('网络请求失败');
//         console.log(error)
//     }
// };
const deleteOrder = async (orderId) => {
    try {
        const res = await deleteOrderApi(orderId);
        if (res.data) {
            ElMessage.success('订单删除成功');
            await fetchOrderData(); // 刷新订单数据
        } else {
            ElMessage.error('订单删除失败');
        }
    } catch (error) {
        ElMessage.error('网络请求失败');
    }
};

const addOrderVisible = ref(false);
const currentOrder = ref({
    vehicle_id: '',
    user_id: '',
    total_cost: 0,
    status: false,
    payment_status: false
});

const insertOrder = () => {
    currentOrder.value = {
        vehicle_id: '',
        user_id: '',
        total_cost: 0,
        status: false,
        payment_status: false,
        taskTypes: [] // 用于存储选中的工种
    };
    addOrderVisible.value = true;
};

const submitInsertOrderForm = async () => {
    try {
        let submit = {
            order: {
                vehicle_id: currentOrder.value.vehicle_id,
                user_id: currentOrder.value.user_id,
                total_cost: parseFloat(currentOrder.value.total_cost) || 0, // 确保总费用是数字
                status: currentOrder.value.status,
                payment_status: currentOrder.value.payment_status
            },
            taskTypes: currentOrder.value.taskTypes // 这里可以根据实际需求添加工种类型
        }
        const res = await createOrderApi(submit);
        if (res.data) {
            ElMessage.success('维修订单新增成功');
            addOrderVisible.value = false;
            await fetchOrderData(); // 刷新订单数据
        } else {
            ElMessage.error('维修订单新增失败');
        }
    } catch (error) {
        ElMessage.error('网络请求失败');
    }
};

// 表单验证规则
const userRules = {
    username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
    password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
};

const repairPersonRules = {
    username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
    password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
    specialty: [{ required: true, message: '工种不能为空', trigger: 'blur' }],
    hourly_rate: [
        { required: true, message: '时薪不能为空', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (!value || isNaN(Number(value))) {
                    callback(new Error('时薪必须是数字'));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ]
};
const userForm = ref(null);
const repairPersonForm = ref(null);
const insertUserForm = ref(null);
const insertRepairPersonForm = ref(null);
// 提交用户表单
const submitUserForm = async () => {
    const form = userForm.value;
    form.validate(async (valid) => {
        if (valid) {
            try {
                const res = await updateUserApi(currentUser.value);
                if (res.data) {
                    ElMessage.success('用户信息修改成功');
                    changeUserVisible.value = false;
                    await fetchUserData(); // 刷新用户数据
                } else {
                    ElMessage.error('用户信息修改失败');
                }
            } catch (error) {
                ElMessage.error('网络请求失败');
            }
        } else {
            ElMessage.warning('请检查表单填写是否正确');
        }
    });
};

const submitInsertUserForm = async () => {
    const form = insertUserForm.value;
    form.validate(async (valid) => {
        if (valid) {
            try {
                let submit = {
                    user_id: currentUser.value.user_id,
                    username: currentUser.value.username,
                    password: currentUser.value.password,
                    userRole: "USER"
                };
                console.log(submit)
                const res = await registerApi(submit);
                if (res.data) {
                    ElMessage.success('用户信息新增成功');
                    addUserVisible.value = false;
                    await fetchUserData(); // 刷新用户数据
                } else {
                    ElMessage.error('用户信息新增失败');
                }
            } catch (error) {
                ElMessage.error('网络请求失败');
            }
        } else {
            ElMessage.warning('请检查表单填写是否正确');
        }
    });
};

// 提交维修人员表单
const submitRepairPersonForm = async () => {
    const form = repairPersonForm.value;
    if (!form) {
        ElMessage.error('表单未正确加载');
        return;
    }
    form.validate(async (valid) => {
        if (valid) {
            try {
                // 将工种从中文映射成英文
                const specialtyKey = Object.keys(typeLabelMap).find(
                    key => typeLabelMap[key] === currentRepairPerson.value.specialty
                );
                let submit = {
                    user_id: currentRepairPerson.value.user_id,
                    username: currentRepairPerson.value.username,
                    password: currentRepairPerson.value.password,
                    repair_person_id: currentRepairPerson.value.repair_person_id,
                    specialty: specialtyKey || currentRepairPerson.value.specialty,
                    hourly_rate: parseFloat(currentRepairPerson.value.hourly_rate) || 0, // 确保时薪是数字
                    userRole: "REPAIR_PERSON"
                };
                const res = await updateRepairPersonApi(submit);
                if (res.data) {
                    ElMessage.success('维修人员信息修改成功');
                    changeRepairPersonVisible.value = false;
                    await fetchRepairPersonData(); // 刷新维修人员数据
                } else {
                    ElMessage.error('维修人员信息修改失败');
                }
            } catch (error) {
                ElMessage.error('网络请求失败');
            }
        } else {
            ElMessage.warning('请检查表单填写是否正确');
        }
    });
};

const submitInsertRepairPersonForm = async () => {
    const form = insertRepairPersonForm.value;
    form.validate(async (valid) => {
        if (valid) {
            try {
                let submit = {
                    user_id: currentRepairPerson.value.user_id,
                    username: currentRepairPerson.value.username,
                    password: currentRepairPerson.value.password,
                    repair_person_id: currentRepairPerson.value.repair_person_id,
                    specialty: currentRepairPerson.value.specialty,
                    hourly_rate: parseFloat(currentRepairPerson.value.hourly_rate) || 0, // 确保时薪是数字
                    userRole: "REPAIR_PERSON"
                };
                const res = await createRepairPersonApi(submit);
                if (res.data) {
                    ElMessage.success('维修人员信息插入成功');
                    addRepairPersonVisible.value = false;
                    await fetchRepairPersonData(); // 刷新维修人员数据
                } else {
                    ElMessage.error('维修人员信息插入失败');
                }
            } catch (error) {
                ElMessage.error('网络请求失败');
            }
        } else {
            ElMessage.warning('请检查表单填写是否正确');
        }
    });
};

// 获取车型统计数据
const fetchVehicleStatistics = async () => {
    try {
        const res = await getVmodelsApi;
        vehicleModelStatistics.value = res.data;
        vehicleModelStatistics.value = res.data.map(item => ({
            ...item,
            theMostRiskType: typeLabelMap[item.theMostRiskType] || "无" // 转换最常见故障类型
        }));} catch (error) {
        ElMessage.error('车型数据加载失败');
    }
};

// 获取订单数据
const fetchOrderData = async () => {
    try {
        const res = await getAllOrdersApi();
        repairOrderData.value = res.data;
    } catch (error) {
        ElMessage.error('订单数据加载失败');
    }
};

// 获取负面反馈数据
const fetchNegativeFeedbacks = async () => {
    try {
        const res = await getNegativeFeedbackApi;
        negativeFeedbacks.value = res.data;
    } catch (error) {
        ElMessage.error('工单数据加载失败');
    }
};

// 获取所有用户信息
const fetchUserData = async () => {
    try {
        const res = await getAllUsersApi();
        userData.value = res.data;
    } catch (error) {
        ElMessage.error('用户数据加载失败');
    }
};

const fetchRepairPersonData = async () => {
    try {
        const res = await getAllRepairPersonsApi();
        repairPersonData.value = res.data
            .map(item => ({
                ...item,
                specialty: typeLabelMap[item.specialty] || item.specialty // 转换工种
            }));
    } catch (error) {
        ElMessage.error('维修人员数据加载失败');
    }
};

// 获取工种统计数据
const fetchTaskTypeData = async (month) => {
    try {
        const res = await getTaskTypeAssignmentApi(month);
        taskTypeAssignments.value = res.data;
    } catch (error) {
        ElMessage.error('工种数据加载失败');
    }
};

// 监听月份变化
watch(selectedMonth, (newVal) => {
    fetchTaskTypeData(newVal);
});

// 过滤负面反馈工单
const filteredNegativeFeedbacks = computed(() => {
    if (!filterRepairPersonId.value) return negativeFeedbacks.value;
    return negativeFeedbacks.value.filter(item =>
        item.repairPersonId.toString().includes(filterRepairPersonId.value.trim())
    );
});

// 初始化数据
onMounted(() => {
    fetchVehicleStatistics();
    fetchNegativeFeedbacks();
    fetchTaskTypeData(selectedMonth.value);
    fetchUserData();
    fetchRepairPersonData();
    fetchOrderData();
    fetchVehicleData();
    fetchPartData();
});

const goToTimeCost = () => {
    router.push('/timeCost');
}

const goToCostAnalysis = () => {
    router.push('/costAnalysis');
}

const handleLogout = () => {
    // 退出逻辑
    router.push('/login');
};

// 车辆逻辑

const vehicleData = ref([]);
const addVehicleVisible = ref(false);
const changeVehicleVisible = ref(false);
const currentVehicle = ref({
    vehicle_id: null,
    user_id: '',
    license_plate: '',
    model: '',
    manufacture_year: null
});

const vehicleRules = {
    user_id: [{ required: true, message: '用户ID不能为空', trigger: 'blur' }],
    license_plate: [{ required: true, message: '车牌号不能为空', trigger: 'blur' }],
    model: [{ required: true, message: '车型不能为空', trigger: 'blur' }],
    manufacture_year: [
        { required: true, message: '生产年份不能为空', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (!value || isNaN(Number(value))) {
                    callback(new Error('生产年份必须是数字'));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ]
};

const fetchVehicleData = async () => {
    try {
        const res = await getAllVehiclesApi();
        vehicleData.value = res.data;
    } catch (error) {
        ElMessage.error('车辆数据加载失败');
    }
};

const insertVehicle = () => {
    currentVehicle.value = {
        vehicle_id: null,
        user_id: '',
        license_plate: '',
        model: '',
        manufacture_year: null
    };
    addVehicleVisible.value = true;
};

const changeVehicleInfo = (vehicle) => {
    currentVehicle.value = { ...vehicle };
    changeVehicleVisible.value = true;
};

const closeInsertVehicleDialog = () => {
    addVehicleVisible.value = false;
};

const closeVehicleDialog = () => {
    changeVehicleVisible.value = false;
};

const submitInsertVehicleForm = async () => {
    try {
        const res = await createVehicleApi(currentVehicle.value);
        if (res.data) {
            ElMessage.success('车辆新增成功');
            addVehicleVisible.value = false;
            await fetchVehicleData();
        } else {
            ElMessage.error('车辆新增失败');
        }
    } catch (error) {
        ElMessage.error('网络请求失败');
    }
};

const submitVehicleForm = async () => {
    try {
        const res = await updateVehicleApi(currentVehicle.value);
        if (res.data) {
            ElMessage.success('车辆信息修改成功');
            changeVehicleVisible.value = false;
            await fetchVehicleData();
        } else {
            ElMessage.error('车辆信息修改失败');
        }
    } catch (error) {
        ElMessage.error('网络请求失败');
    }
};

const deleteVehicle = async (vehicleId) => {
    try {
        const res = await deleteVehicleApi(vehicleId);
        if (res.data) {
            ElMessage.success('车辆删除成功');
            await fetchVehicleData();
        } else {
            ElMessage.error('车辆删除失败');
        }
    } catch (error) {
        ElMessage.error('网络请求失败');
    }
};
</script>

<style scoped>
/* 原有样式保持不变 */
.custom-column {
    width: 200px;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.dialog-footer {
    text-align: right;
}

.table-container {
    padding: 0 20px;
    margin-bottom: 30px;
}
</style>